//
//  TextView.swift
//  weibobbaj
//
//  Created by Tiffany宝 on 16/4/26.
//  Copyright © 2016年 Tiffany. All rights reserved.
//

import UIKit

class TextView: UITextView {
    
    var placeholder: String?{
        
        didSet{
            
            placeholderLabel.text = placeholder
        }
    }
    
    override var font: UIFont?{
        
        didSet{
            
            placeholderLabel.font = font
        }
    }
    
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
        
//        backgroundColor = UIColor.darkGrayColor()
        
        //添加控件
        addSubview(placeholderLabel)
        
        //添加约束
        placeholderLabel.snp_makeConstraints { (make) -> Void in
            
            make.top.equalTo(self).offset(10)
            make.leading.equalTo(self).offset(5)
//            make.width.equalTo(self).offset(-10)
        }
        
        //通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "changeText", name: UITextViewTextDidChangeNotification, object: nil)
    }
    
    @objc private func changeText(){
        
//        print("changeText")
        placeholderLabel.hidden = hasText()
    }
    
    // MARK: - 移除通知
    deinit{
        
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    //懒加载占位文字
    private lazy var placeholderLabel: UILabel = {
        
        let mrgin = 5
        let placeholder = UILabel(textFont: 9, textColor: UIColor.lightGrayColor(),preferredMaxLayoutWidth: SCREENW - 2 * margin)
        
        placeholder.numberOfLines = 0
        
        return placeholder
    }()
}
